package com.bungarus.busi;

import com.bungarus.Transfer;
import com.bungarus.model.BungarusClientException;
import com.bungarus.model.MessageBuilder;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.log4j.Logger;

/**
 * Created by tang on 2018/11/29.
 */
public class TransferClientHeartbeatHandler extends ChannelInboundHandlerAdapter {
    Logger logger = Logger.getLogger(TransferClientHeartbeatHandler.class);

    private final BaseClient client;

    public TransferClientHeartbeatHandler(BaseClient client) {
        this.client = client;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            ctx.writeAndFlush(MessageBuilder.buildHeartbeatPingMessage(Transfer.TAG))
                    .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        }
        else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        try {
            this.client.connectNextNode(ctx.channel().eventLoop());
        }
        catch (BungarusClientException e){
            e.printStackTrace();
        }
        super.channelInactive(ctx);
    }

}
